import React, { useState, useEffect } from 'react';
import { Modal, Upload, Button, Progress, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import request from '@/utils/request';

interface ImportDataModalProps {
  visible: boolean;
  onCancel: () => void;
  datasetId: number;
  treeUuid: string;
  onSuccess?: () => void;
}

const ImportDataModal: React.FC<ImportDataModalProps> = ({ visible, onCancel, datasetId, treeUuid, onSuccess }) => {
  const [fileList, setFileList] = useState<any[]>([]);
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    if (visible) {
      setFileList([]);
    }
  }, [visible]);

  const uploadSingleFile = async (file: any) => {
    if (!datasetId || !treeUuid) {
      throw new Error('数据集ID和树UUID不能为空');
    }

    const formData = new FormData();
    formData.append('files', file.originFileObj);
    formData.append('dataset_id', datasetId.toString());
    formData.append('tree_uuid', treeUuid);

    const response = await request.post('/PDS/DataSetFileDataUpload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 200) {
      return true;
    } else {
      throw new Error(response.data.msg || '上传失败');
    }
  };

  const handleUpload = async (files: any[]) => {
    if (!datasetId || !treeUuid) {
      message.error('数据集ID和树UUID不能为空');
      return;
    }

    if (files.length === 0) {
      message.warning('请先选择要上传的文件');
      return;
    }

    setUploading(true);
    let successCount = 0;
    let failCount = 0;

    for (const file of files) {
      try {
        await uploadSingleFile(file);
        successCount++;
      } catch (error) {
        console.error('Upload error:', error);
        message.error(error instanceof Error ? error.message : '上传失败');
        failCount++;
      }
    }

    if (successCount > 0) {
      message.success(`成功上传 ${successCount} 个文件`);
      if (failCount > 0) {
        message.warning(`${failCount} 个文件上传失败`);
      }
      setFileList([]);
      onSuccess?.();
      onCancel();
    } else {
      message.error('文件上传失败');
    }
    setUploading(false);
  };

  const customRequest = async (options) => {
    const { file, onSuccess, onError, onProgress } = options;
    const formData = new FormData();
    formData.append('file', file);
    formData.append('dataset_id', datasetId + '');
    formData.append('tree_uuid', treeUuid);
    try {
      const response = await request.post('/PDS/DataSetFileDataUpload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: localStorage.getItem('token') || ''
        },
        onUploadProgress: (event) => {
          if (event.total > 0) {
            const percent = Math.round((event.loaded / event.total) * 100);
            onProgress({ percent });
          }
        }
      });
      if (response.data.code === 200) {
        onSuccess(response.data, file);
      } else {
		message.error(response.data.msg);
        onError({ msg: response.data.msg || '上传失败', response: response.data });
      }
    } catch (err) {
		if (err.message) {
			message.error(err.message || '');
		}
      onError({ msg: '网络错误', response: err });
    }
  };

  const handleFileChange = (info: any) => {
    if (!datasetId || !treeUuid) {
      message.error('数据集ID和树UUID不能为空');
      return;
    }

    setFileList(info.fileList);

    info.fileList.forEach((file: any) => {
      if (file.status === 'error' && file.response?.msg) {
        message.error(file.response.msg);
      }
    });

    const allFilesDone = info.fileList.every((file: any) => file.status === 'done' || file.status === 'error');

    if (allFilesDone && info.fileList.length > 0) {
      const successCount = info.fileList.filter((file: any) => file.status === 'done').length;
      const failCount = info.fileList.filter((file: any) => file.status === 'error').length;

      if (successCount > 0) {
        message.success(`成功上传 ${successCount} 个文件`);
        if (failCount > 0) {
          message.warning(`${failCount} 个文件上传失败`);
        }
        onSuccess?.();
        onCancel();
      } else {
        message.error('文件上传失败');
      }
    }
  };

  const handleFileRemove = (file: any) => {
    setFileList((prev) => prev.filter((item) => item.uid !== file.uid));
  };

  return (
    <Modal title="导入数据" open={visible} onCancel={onCancel} footer={null} width={600} centered destroyOnHidden>
      <div style={{ display: 'flex', alignItems: 'flex-start' }}>
        <div style={{ width: 100, fontSize: 18, marginTop: 16 }}>批量导入：</div>
        <div style={{ flex: 1 }}>
          <Upload.Dragger
            multiple
            fileList={fileList}
            onChange={handleFileChange}
            onRemove={handleFileRemove}
            accept="*"
            style={{ marginBottom: 16 }}
            customRequest={customRequest}
            data={{
              dataset_id: datasetId,
              tree_uuid: treeUuid
            }}
            headers={{
              token: localStorage.getItem('token') || ''
            }}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined style={{ fontSize: 48, color: '#1890ff' }} />
            </p>
            <p>
              将文件拖到此处或点击上传
              <br />
              支持所有类型的文件
            </p>
          </Upload.Dragger>
          {/* {fileList.map(file => (
            <div key={file.uid} style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
              <span style={{ flex: 1 }}>{file.name}</span>
              <Progress percent={file.percent || 100} size="small" style={{ width: 120, margin: '0 8px' }} />
              <Button type="text" danger size="small" onClick={() => handleFileRemove(file)}>删除</Button>
            </div>
          ))} */}
          <div style={{ textAlign: 'center', marginTop: 24 }}>
            <Button onClick={onCancel}>关闭</Button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default ImportDataModal;
